import { Component, Input, Output, OnInit, ViewChild, EventEmitter, OnChanges, SimpleChanges, ChangeDetectionStrategy } from '@angular/core';
import { EnvVariable } from "../class/instance";

@Component({
  selector: 'app-environment-variables',
  changeDetection: ChangeDetectionStrategy.OnPush,
  templateUrl: './environment-variables.component.html',
  styleUrls: ['./environment-variables.component.less']
})

export class EnvironmentVariablesComponent implements OnInit {

  @Input() envVariableData: EnvVariable[] = [];
  @Input() needValid:boolean = false; //初始化的时候是否需要校验，当是从父组件的确定按钮触发后，传递过来的，则要校验，不仅输入框报红，提示也出现报红；如果是通过如创建函数初始化时加载的，则开始不校验，在输入时校验，校验不通过，输入框报红且提示出现报红
  @Input() isInForm:boolean = false; //控制nzi-help样式，在创建函数页面，使用 env-help样式，在配置弹窗也，使用dnv-config-help
  @Output() getEnvVariables = new EventEmitter<any>();
  outputEnvVariables: EnvVariable[] = [];
  i = 0;
  inputFirstInit:boolean = true;
  envVariableInitData: EnvVariable[] = [];
  keyRegExp = new RegExp('^[a-zA-Z][a-zA-Z0-9_]{1,63}$');
  keyValid:boolean = true;
  valueValid:boolean = true;
  duplicationValidator:boolean = false; //是否有重复的key/value对
  maxEnvNumber = 100;
  finallyValid:boolean = true; //最中传递的值，有没有校验都通过

  constructor() { }

  ngOnInit() {
    this.operateInitData();
    if(this.needValid){
      this.validInitData();
    }
  }

  ngOnChanges(simpleChanges: SimpleChanges){
    if(simpleChanges.envVariableData){
      if(simpleChanges.envVariableData.currentValue != simpleChanges.envVariableData.previousValue){
        this.operateInitData();
        if(this.needValid){
          this.validInitData();
        }
      }
    }
  }

  operateInitData(){
    this.envVariableInitData = [];
    this.i = this.envVariableData.length;
    let allowAddRow:boolean = true;
    for(let i = 0; i< this.envVariableData.length ; i++){
      if(this.envVariableData[i].key != undefined && this.envVariableData[i].value != undefined){
        let itemData: EnvVariable = { id:'', key:'',value:'' };
        itemData['id'] = i + '';
        itemData['key'] = this.envVariableData[i].key;
        itemData['value'] = this.envVariableData[i].value
        ;
        this.envVariableInitData.push(itemData);
      }
      if(!this.envVariableData[i]['key'] && !this.envVariableData[i]['value']){
        allowAddRow = false;
      }
    }
    //如果 envVariableData 是空的，那么上一次的校验结果要去掉重置;应用于发生在ngOnChanges中
    if(this.envVariableData.length <= 0){
      this.keyValid = true;
      this.valueValid = true;
      this.duplicationValidator = false;
    }
    if(allowAddRow){
      this.addRow();
    }
  }

  validInitData(){
    //校验key和value,目前，输入在创建函数那儿，点击确定后，如果环境变量校验不通过，则输入框报红，但是提示不报红。当前操作，重在将提示文字显示报红
    this.keyValid = true;
    this.valueValid = true;
    for(let item of this.envVariableInitData){
      //除 key 和 value都为undefined外，其余都校验，因为这些是未输入过的，刚开始添加的框框，供输入使用的，没有加入到最终的参数中
      //校验key
      if(!(item['key'] == undefined && item['value'] == undefined)){
        if(!this.keyValidator(item)){
          this.keyValid = false;
        }
        //校验value
        if(!this.valueValidator(item)){
          this.valueValid = false;
        }
        //校验重复
        if(this.duplicationValid(item)){
          this.duplicationValidator = true;
        }
      }
    }
  }

  addRow(): void {
    this.envVariableInitData = [
      ...this.envVariableInitData,
      {
        id: `${this.i}`,
        key: undefined ,
        value: undefined ,
      }
    ];
    this.i++;
  }

  inputEnvVariables(id){
    this.inputFirstInit = false;
    if((this.envVariableInitData.length > 0 && this.envVariableInitData[this.envVariableInitData.length-1].id === id) || [...this.envVariableInitData].length <= 1){
      this.addRow();
    }
    this.emitEnvVariables( );
  }

  keyChange(data){
    //由2-64个字符组成，以字母开始，包含字母、数字或者“_”
    if(data.key && !(data.key && this.keyRegExp.test(data.key))){
      this.keyValid = false;
    }else if(data.key === ''){
      this.keyValid = false;
    }else{
      this.keyValid =true;
    }
    this.duplicationValid(data);
  }

  keyValidator(data):boolean{
    //由2-64个字符组成，以字母开始，包含字母、数字或者“_”
    if(!data.key || (data.key && !(data.key && this.keyRegExp.test(data.key)))){
      this.finallyValid = false;
      return false;
    }
    return true;
  }

  valueChange(data){
    if(data.value === ''){
      this.valueValid = false;
    }else{
      this.valueValid = true;
    }
    this.duplicationValid(data);
  }

  //只判断一次
  valueValidator(data):boolean{
    if(data.value === '' || !data.value){
      this.finallyValid = false;
      return false;
    }
    return true;
  }

  duplicationValid(data):boolean{
    let valid:boolean = false , sameNumber:number = 0;
    if(data['key'] == undefined && data['value'] == undefined){ //如果当前data的键值都是 undefined,说明是新添加的，不进行校验，不重复
      return false;
    }
    for(let i = 0; i < this.envVariableInitData.length; i++){
      let item = this.envVariableInitData[i];
      let itemKey = item['key'] || '',itemValue = item['value'] || '',
          dataKey = data['key'] || '', dataValue = data['value'] || '';
      if( itemKey == dataKey && itemValue == dataValue && !(item['key'] == undefined && item['value'] == undefined)){
        sameNumber++;
      }
    }
    if(sameNumber >= 2){
      valid = true;
    }
    this.duplicationValidator = valid;
    return valid;
  }

  emitEnvVariables( ){
    this.finallyValid = true;
    //去掉id
    this.outputEnvVariables= [];
    //加校验，将是否有红色报错提示输出
    let valid: boolean = true;
    for(let item of this.envVariableInitData){
      let t = { id:'',key:'',value:'' };
      if(!(item['key'] == undefined && item['value'] == undefined)){
        t['id'] = item['id'];
        t['key'] = item['key'] || '';
        t['value'] = item['value'] || '';
        this.keyValidator(t);
        this.valueValidator(t);
        this.duplicationValid(t)
        this.outputEnvVariables.push(t);
      }
      //校验
      if(!this.finallyValid || this.duplicationValidator || this.outputEnvVariables.length > this.maxEnvNumber){
        valid = false;
      }

    }
    for(let item of this.outputEnvVariables){
      if(item.hasOwnProperty('id')){
        delete item['id'];
      }
    }
    this.getEnvVariables.emit({envVariableList: this.outputEnvVariables,valid:valid});
  }

  deleteRow(id: string): void {
    this.envVariableInitData = this.envVariableInitData.filter(d => d.id !== id);
    //删除后，进行校验，控制下面提示文字的显示与报红
    this.deleteRowValid();
    this.emitEnvVariables( );
  }

  deleteRowValid(){
    this.keyValid = true;
    this.valueValid = true;
    this.duplicationValidator = false;
    for(let i =0 ; i< this.envVariableInitData.length ; i++){
      let item = this.envVariableInitData[i];
      if(!(item['key'] == undefined && item['value'] == undefined)){
        if(!this.keyValidator(item)){
          this.keyValid = false;
        }
        if(!this.valueValidator(item)){
          this.valueValid = false;
        }
        if(this.duplicationValid(item)){
          this.duplicationValidator = true;
        }
      }
    }
  }

}
